import express, { Router, Request, Response, NextFunction } from 'express';
import { User } from '../model';
import createError from 'http-errors';
import { INTERNAL_SERVER_ERROR } from 'http-status-codes';
let router: Router = express.Router();
//获取所有用户 GET /users
router.get('/', async (_request: Request, response: Response, next: NextFunction) => {
    try {
        let users = await User.findAll();
        response.json({
            success: true,
            data: users
        });
    } catch (error) {
        next(error);
    }

});
//获取某个用户 GET /users/:id
router.get('/:id', async (request: Request, response: Response, next: NextFunction) => {
    try {
        let id = request.params.id;
        let user = await User.findByPk(id);
        response.json({
            success: true,
            data: user
        });
    } catch (error) {
        next(error);
    }

});
//添加一个用户 POST /users
router.post('/', async (request: Request, response: Response, next: NextFunction) => {
    try {
        let user = request.body;
        user = await User.create(user);//insert语句插到数据库
        response.json({
            success: true,
            data: user
        });
    } catch (error) {
        next(error);
    }

});
//更新一个用户 PUT /users/:id
router.put('/:id', async (request: Request, response: Response, next: NextFunction) => {
    try {
        let id = request.params.id;
        let updateInfo = request.body;
        let user = await User.findByPk(id);
        user = await user.update(updateInfo);//update users set  where id=?
        response.json({
            success: true,
            data: user
        });
    } catch (error) {
        next(error);
    }

});
//删除一个用户 DELETE /users/:id
router.delete('/:id', async (request: Request, response: Response, next: NextFunction) => {
    try {
        let id = request.params.id;
        let user = await User.findByPk(id);
        if (!user) {
            return next(createError(INTERNAL_SERVER_ERROR));
        }
        user = await user.destroy()//delete from users where id=?
        response.json({
            success: true,
            data: user
        });
    } catch (error) {
        next(error);
    }
});
export default router;